package com.ruoyi.legal.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ruoyi.common.core.page.Pages;
import com.ruoyi.common.core.page.Query;
import com.ruoyi.common.query.QueryTool;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.*;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.legal.domain.*;
import com.ruoyi.legal.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.legal.mapper.PackMapper;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;

/**
 * 打包备份Service业务层处理
 * 
 * @author xwj
 * @date 2025-05-10
 */
@Service
public class PackServiceImpl extends ServiceImpl<PackMapper, Pack> implements IPackService {
    @Autowired
    private PackMapper packMapper;
    @Autowired
    private IAjtzService ajtzService;
    @Autowired
    private IPackAjtzService packAjtzService;
    @Autowired
    private IYstzService ystzService;
    @Autowired
    private IPackYstzService packYstzService;
    @Autowired
    private IXjclService xjclService;
    @Autowired
    private IPackXjclService packXjclService;

    /**
     * 查询打包备份
     * 
     * @param id 打包备份主键
     * @return 打包备份
     */
    @Override
    public Pack selectPackById(Long id) {
        return packMapper.selectPackById(id);
    }

    /**
     * 查询打包备份列表
     * 
     * @param pack 打包备份
     * @return 打包备份
     */
    @Override
    public List<Pack> selectPackList(Pack pack) {
        return packMapper.selectPackList(pack);
    }

    /**
     * 新增打包备份
     * 
     * @param pack 打包备份
     * @return 结果
     */
    @Override
    public Pack insertPack(Pack pack) {

      //  packMapper.insertPack(pack);
    save(pack);
    return pack;
    }

    /**
     * 修改打包备份
     * 
     * @param pack 打包备份
     * @return 结果
     */
    @Override
    public Pack updatePack(Pack pack) {

      //  packMapper.updatePack(pack);
        updateById(pack);
        return pack;
    }

    /**
     * 批量删除打包备份
     * 
     * @param ids 需要删除的打包备份主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deletePackByIds(Long[] ids) {
        packAjtzService.deleteByPackIds(ids);
        packYstzService.deleteByPackIds(ids);
        packXjclService.deleteByPackIds(ids);

        return packMapper.deletePackByIds(ids);
    }

    /**
    * 条件删除
    * @param pack 打包备份
    * @return
    */
    @Override
    public int delete(Pack pack) {
        QueryWrapper<Pack> qw = new QueryWrapper<>();
        QueryTool.condition(qw, pack);
        return baseMapper.delete(qw);
    }

    /**
     * mp分页
     * @param pack 打包备份
     * @return
     */
    @Override
    public Pages<Pack> queryPage(Pack pack) {
        QueryWrapper<Pack> qw = new QueryWrapper<>();
        QueryTool.condition(qw, pack);
        IPage<Pack> ipage = new Query<Pack>().getPage(pack);

        IPage<Pack> page = this.page(
                ipage,
                qw
        );
        return new Pages<>(page);
    }

    @Override
    @Transactional
    public void addPack(Pack pack) {
        Integer type = pack.getType();
        if(type == 1) {
            this.addPackAjtz(pack);
        } else if(type == 2){
            this.addPackYstz(pack);
        } else {
            this.addPackXjcl(pack);
        }
    }

    /**
     * 案件台账-备份
     * 1、查询数据
     * 2、插入数据
     * @param pack
     */

    private void addPackAjtz(Pack pack) {
        String month = pack.getEffectMonth();

        Ajtz condition = new Ajtz();
        condition.setMonthTime(month);

        List<Ajtz> ajtzList = ajtzService.selectAjtzList(condition);
        Map<String, List<Ajtz>> map = new HashMap<>();

        for(Ajtz ajtz: ajtzList) {
            String ksmc = ajtz.getKsmc();
            if(StringUtils.isEmpty(ksmc)) {
                continue;
            }

            map.computeIfAbsent(ksmc, k -> new ArrayList<>());
            map.get(ksmc).add(ajtz);
        }

        Date now = new Date();


        map.forEach((key, list) -> {
            Pack _pack = packMapper.findPack(key, pack.getType());
            if(_pack == null) {
                _pack = new Pack();
                _pack.setCreateId(pack.getCreateId());
                _pack.setCreateTime(now);
                _pack.setCreateBy(pack.getCreateBy());
            } else {
                _pack.setUpdateId(pack.getCreateId());
                _pack.setUpdateTime(now);
                _pack.setUpdateBy(pack.getCreateBy());
            }

            _pack.setEffectMonth(month);
            _pack.setDeptName(key);
            _pack.setType(pack.getType());

            saveOrUpdate(_pack);

            List<PackAjtz> packAjtzs = new ArrayList<>();
            for(Ajtz ajtz: list) {
                PackAjtz packAjtz = new PackAjtz();
                BeanUtil.copyProperties(ajtz, packAjtz);
                packAjtz.setPackId(_pack.getId());
                packAjtzs.add(packAjtz);
            }
            packAjtzService.saveBatch(packAjtzs);
        });
    }

    private void addPackYstz(Pack pack) {
        String month = pack.getEffectMonth();

        Ystz condition = new Ystz();
        condition.setMonthTime(month);

        List<Ystz> ystzList = ystzService.selectYstzList(condition);
        Map<String, List<Ystz>> map = new HashMap<>();

        for(Ystz ystz: ystzList) {
            String ksmc = ystz.getBgks();
            if(StringUtils.isEmpty(ksmc)) {
                continue;
            }

            map.computeIfAbsent(ksmc, k -> new ArrayList<>());
            map.get(ksmc).add(ystz);
        }

        Date now = new Date();

        map.forEach((key, list) -> {
            Pack _pack = packMapper.findPack(key, pack.getType());
            if(_pack == null) {
                _pack = new Pack();
                _pack.setCreateId(pack.getCreateId());
                _pack.setCreateTime(now);
                _pack.setCreateBy(pack.getCreateBy());
            } else {
                _pack.setUpdateId(pack.getCreateId());
                _pack.setUpdateTime(now);
                _pack.setUpdateBy(pack.getCreateBy());
            }
            _pack.setEffectMonth(month);
            _pack.setDeptName(key);
            _pack.setType(pack.getType());

            insertPack(_pack);

            List<PackYstz> packYstzs = new ArrayList<>();
            for(Ystz ystz: list) {
                PackYstz packYstz = new PackYstz();
                BeanUtil.copyProperties(ystz, packYstz);
                packYstz.setPackId(_pack.getId());
                packYstzs.add(packYstz);
            }
            packYstzService.saveBatch(packYstzs);
        });
    }

    private void addPackXjcl(Pack pack) {
        String month = pack.getEffectMonth();

        Xjcl condition = new Xjcl();
        condition.setMonthTime(month);

        List<Xjcl> xjclList = xjclService.selectXjclList(condition);

        Date now = new Date();

        Pack _pack = packMapper.findPack(null, pack.getType());
        if(_pack == null) {
            _pack = new Pack();
            _pack.setCreateId(pack.getCreateId());
            _pack.setCreateTime(now);
            _pack.setCreateBy(pack.getCreateBy());
        } else {
            _pack.setUpdateId(pack.getCreateId());
            _pack.setUpdateTime(now);
            _pack.setUpdateBy(pack.getCreateBy());
        }
        _pack.setEffectMonth(month);
        _pack.setType(pack.getType());

        insertPack(_pack);

        List<PackXjcl> packXjcls = new ArrayList<>();
        for(Xjcl xjcl: xjclList) {
            PackXjcl packXjcl = new PackXjcl();
            BeanUtil.copyProperties(xjcl, packXjcl);
            packXjcl.setPackId(_pack.getId());
            packXjcls.add(packXjcl);
        }
        packXjclService.saveBatch(packXjcls);
    }
    /**
     * 删除打包备份信息
     * 
     * @param id 打包备份主键
     * @return 结果
     */
    @Override
    public int deletePackById(Long id) {
        return packMapper.deletePackById(id);
    }


    @Override
    public void exportPackAjtz(HttpServletResponse response, Long id) {
        PackAjtz param = new PackAjtz();
        param.setPackId(id);
        List<PackAjtz> list = packAjtzService.selectPackAjtzList(param);

        ExcelUtil<PackAjtz> util = new ExcelUtil<PackAjtz>(PackAjtz.class);
        util.exportExcel(response, list, "案件台账打包数据");
    }

    @Override
    public void exportPackYstz(HttpServletResponse response, Long id) {
        PackYstz param = new PackYstz();
        param.setPackId(id);
        List<PackYstz> list = packYstzService.selectPackYstzList(param);

        ExcelUtil<PackYstz> util = new ExcelUtil<>(PackYstz.class);
        util.exportExcel(response, list, "移送台账打包数据");
    }

    @Override
    public void exportPackXjcl(HttpServletResponse response, Long id) {
        PackXjcl param = new PackXjcl();
        param.setPackId(id);
        List<PackXjcl> list = packXjclService.selectPackXjclList(param);

        ExcelUtil<PackXjcl> util = new ExcelUtil<>(PackXjcl.class);
        util.exportExcel(response, list, "虚假材料打包数据");
    }

    /**
     * 定时任务-打包案件
     */
    @Override
    public void taskPackAjtz() {
        Date now = DateUtil.lastMonth(); // 上个月
        String month = DateUtil.format(now, "yyyy-MM");
        Pack pack = new Pack();
        pack.setType(1);
        pack.setEffectMonth(month);
        this.addPackAjtz(pack);
    }

    @Override
    public void taskPackYstz() {
        Date now = DateUtil.lastMonth(); // 上个月
        String month = DateUtil.format(now, "yyyy-MM");
        Pack pack = new Pack();
        pack.setType(2);
        pack.setEffectMonth(month);

        this.addPackYstz(pack);
    }

    @Override
    public void taskPackXjcl() {
        Date now = DateUtil.lastMonth(); // 上个月
        String month = DateUtil.format(now, "yyyy-MM");
        Pack pack = new Pack();
        pack.setType(3);
        pack.setEffectMonth(month);

        this.addPackXjcl(pack);
    }



}
